const sql = require('mssql');
// 拣货开始时间
// const startTime = '2019-07-01 00:00:01.000';
const startTime = '2019-07-04 14:00:01.000';

const getNowFormatDate = () => {
    var date = new Date()
    var seperator1 = '-'
    var seperator2 = ':'
    var month = date.getMonth() + 1
    var strDate = date.getDate()
    if (month >= 1 && month <= 9) {
        month = '0' + month
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = '0' + strDate
    }
    var currentdate =
        date.getFullYear() +
        seperator1 +
        month +
        seperator1 +
        strDate +
        ' ' +
        date.getHours() +
        seperator2 +
        date.getMinutes() +
        seperator2 +
        date.getSeconds()
    return currentdate
}

const setTime = (we, YXQZ) => {
    let nb = ''
    const w = we + 1

    if (w >= 10 && w < 100) {
        nb = `000${w}`
    } else if (w >= 100 && w < 1000) {
        nb = `00${w}`
    } else if (w >= 1000 && w < 10000) {
        nb = `0${w}`
    } else {
        nb = `0000${w}`
    }

    return nb
}

// 补全时间
const repairTime = (time) => {
    return time.toString().length == 1 ? ('0' + time) : time;
}

// 获取时间拼接的年月日
const getNowTimeId = (time) => {
    let nowTime = time ? new Date(time) : new Date();
    let y = nowTime.getFullYear();
    let M = nowTime.getMonth() + 1;
    let d = nowTime.getDate();
    let h = nowTime.getHours();
    let m = nowTime.getMinutes();
    let s = nowTime.getSeconds();
    return {
        msDate: repairTime(m) + repairTime(s),
        date: y.toString().slice(2) + repairTime(M) + repairTime(d),
        halfDate: `${y.toString()}-${repairTime(M)}-${repairTime(d)}`,
        fullDate: `${y.toString()}-${repairTime(M)}-${repairTime(d)} ${repairTime(h)}:${repairTime(m)}:${repairTime(s)}.000`
    }
}

/**
 * 
 *格式化日期
 */
const dateFomat = (fmt, date) => {
    var o = {
        "M+": date.getMonth() + 1,                 //月份   
        "d+": date.getDate(),                    //日   
        "h+": date.getHours(),                   //小时   
        "m+": date.getMinutes(),                 //分   
        "s+": date.getSeconds(),                 //秒   
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度   
        "S": date.getMilliseconds()             //毫秒   
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt + '.000';
}

/**
 * @params {day}距离今天是多少天
 * @description 获取距离今天多少天的时间
 * @value 时间格式
 */

const getDayAgo = (day, type = 'before') => {
    let nowStamp = (new Date()).getTime();

    let threeAgoStamp = type === 'before' ? Number(nowStamp) - Number(day * 24 * 60 * 60 * 1000) : Number(nowStamp) + Number(day * 24 * 60 * 60 * 1000);
    let threeAgoTime = new Date(threeAgoStamp);
    let y = threeAgoTime.getFullYear();
    let M = threeAgoTime.getMonth() + 1;
    let d = threeAgoTime.getDate();
    let h = threeAgoTime.getHours();
    let m = threeAgoTime.getMinutes();
    let s = threeAgoTime.getSeconds();
    return `${y.toString()}-${repairTime(M)}-${repairTime(d)} ${repairTime(h)}:${repairTime(m)}:${repairTime(s)}.000`;
}

/**
 * @params {day}距离今天是多少天
 * @description 获取距离今天多少天的时间
 * @value 时间格式
 */
const createId = async (userId, tableName) => {
    let lastOrderSql = `SELECT TOP 1 ID FROM ${tableName} WHERE ID LIKE '${getNowTimeId().date}${userId}12%' ORDER BY ID DESC`;
    let oldOrder = await sql.query(lastOrderSql);
    let newSerialNum = 1;
    if (oldOrder.recordset.length !== 0) {
        let oldOrderId = oldOrder.recordset[0].ID;
        let oldSerialNum = oldOrderId.slice(oldOrderId.length - 4);
        newSerialNum = Number(oldSerialNum) + 1;
    }
    newSerialNum = newSerialNum.toString();
    newSerialNum = '0000'.slice(0, 4 - newSerialNum.length) + newSerialNum;
    return getNowTimeId().date + userId + '12' + newSerialNum;
}

const createCallNumberId = async (tableName) => {
    let lastOrderSql = `SELECT TOP 1 id FROM ${tableName} WHERE ID LIKE '${getNowTimeId().date}%' ORDER BY id DESC`;
    let oldOrder = await sql.query(lastOrderSql);
    let newSerialNum = 1;
    if (oldOrder.recordset.length !== 0) {
        let oldOrderId = oldOrder.recordset[0].id;
        let oldSerialNum = oldOrderId.slice(oldOrderId.length - 4);
        newSerialNum = Number(oldSerialNum) + 1;
    }
    newSerialNum = newSerialNum.toString();
    newSerialNum = '0000'.slice(0, 4 - newSerialNum.length) + newSerialNum;
    return getNowTimeId().date + newSerialNum;
}

/**
 * @description 创建日志
 * @param {Array}} logList  日志的信息
 */
const createLog = async (logList) => {
    let insertLogSql = ` INSERT INTO log (BM,CZRQ,CZNR)   `;
    logList.forEach((item, ind) => {
        insertLogSql += ` SELECT '${item.userId}','${getNowTimeId().fullDate}','${item.content}'  `;
        if (ind !== logList.length - 1) {
            insertLogSql += ' UNION '
        }
    });
    await sql.query(insertLogSql);
}

module.exports = {
    dateFomat,
    setTime,
    getNowFormatDate,
    getNowTimeId,
    startTime,
    getDayAgo,
    createId,
    createLog,
    createCallNumberId
}

